home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7719 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  65 lines

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: about free()
  5. Date: Wed, 28 Feb 96 12:38:38 GMT
  6. Organization: none
  7. Message-ID: <825511118snz@genesis.demon.co.uk>
  8. References: <31333454.167E@mashie.ece.jhu.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <31333454.167E@mashie.ece.jhu.edu>
  15.            chenyang@mashie.ece.jhu.edu "Chenyang Xu" writes:
  16.  
  17. >Hi, there,
  18. >
  19. >     I have a simple question here.
  20. >
  21. >     I have a function say newarrary() which mallocs an array inside and
  22. >returns a pointer to this arrary. In another function foo.c, the result
  23. >of newarray() is assigned to a pointer ptr. Now after some operations on
  24. >this array. I use free(ptr) to free the memory allocated by newarrary().
  25. >My question is whould this cause a problem, since free() is not freeing
  26. >the same pointer which is allocated by the malloc() although this
  27. >pointer point to the same memory.
  28.  
  29. All that matters is the value of the pointer you pass to free i.e. what
  30. it points to. For example:
  31.  
  32. ...
  33.  
  34. {
  35.     char *ptr1 = malloc(1000);
  36.  
  37.     if (ptr1 != NULL) {
  38.         char *ptr2 = ptr1 + 123;
  39.  
  40.         free(ptr2 - 123);
  41.     }
  42. }
  43.  
  44. This is perfectly legal. The pointer passed to free has the same value as
  45. that returned by malloc and wasn't previously passed to free. After the call
  46. to free() the values of both ptr1 and ptr2 are invalid since they pointed to
  47. an object that has been freed.
  48.  
  49. Note that in the example above:
  50.  
  51.     free(ptr2);
  52.  
  53. is illegal since ptr2 does not contain a value returned by malloc.
  54.  
  55.     free(ptr2-123);
  56.     free(ptr);
  57.  
  58. is illegal because it tries to free the same object twice.
  59.  
  60. -- 
  61. -----------------------------------------
  62. Lawrence Kirby | fred@genesis.demon.co.uk
  63. Wilts, England | 70734.126@compuserve.com
  64. -----------------------------------------
  65.